package com.lzy.cloud.shop.facade;

import com.github.pagehelper.PageInfo;
import com.lzy.cloud.shop.dto.ShopCategoryDto;
import com.lzy.cloud.shop.dto.ShopDto;
import com.lzy.cloud.shop.remote.BaseApi;
import com.lzy.cloud.shop.remote.GoodsApi;
import com.lzy.cloud.shop.service.ShopCategoryService;
import com.lzy.cloud.shop.service.ShopService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ShopFacade {

    @Autowired
    ShopService shopService;
    @Autowired
    ShopCategoryService shopCategoryService;
    @Autowired
    GoodsApi goodsApi;
    @Autowired
    BaseApi baseApi;

    /**
     * 分页查询各模块商户列表
     * @param pager
     * @param shopDto
     * @return
     */
    public List<ShopDto> selectShopList(Pager pager, ShopDto shopDto){
        Ensure.that(shopDto.getCategoryId()).isNotNull("");
        Integer categoryId = shopDto.getCategoryId();
        switch (categoryId) {
            case 1: //房车销售

                break;
            case 2: //房车租赁
                PageInfo<ShopDto> pageInfo = shopService.selectByCategoryId(pager,categoryId,shopDto);
                if(pageInfo != null){
                    List<ShopDto> shopDtoList = pageInfo.getList();
                if (shopDtoList != null && shopDtoList.size() > 0) {
                    for (ShopDto shop : shopDtoList) {
                        Result result = goodsApi.selectCarNumberByShopId(shop.getId());
                        if (result != null && result.getResult() != null) {
                            shop.setCarNumber(Integer.valueOf(result.getResult().toString()));
                        }
                    }
                 }
                 return shopDtoList;
             }
        }
        return null;
    }

    /**
     * 根据id查询详情
     * @param id
     * @return
     */
    public ShopDto detail(Long id){
       //根据id获取商户详情
        ShopDto shopDto = shopService.selectById(id);
       //根据shopId获取营业执照
        Result result = baseApi.selectBusinessLicence(id);
        if(result != null){
            shopDto.setBusinessLicence(String.valueOf(result.getResult()));
        }
       return shopDto;
    }

    /**
     * 添加商户和商户分类
     * @param shopDto
     * @return
     */
    public Long add(ShopDto shopDto) {
        Long id = shopService.addShop(shopDto);
        Ensure.that(id).isNotNull("");
        String[] moduleStr = shopDto.getModuleStr().split(",");
        for (String module:moduleStr) {
            ShopCategoryDto shopCategoryDto = new ShopCategoryDto();
            shopCategoryDto.setShopId(id);
            shopCategoryDto.setCategoryId(Long.valueOf(module));
            shopCategoryService.add(shopCategoryDto);
        }
        return id;
    }
}
